// 插件：每10秒检查并发送未发送的订单邮件
// 放到 server/plugins 下以确保 Nuxt 将其作为服务器插件加载

// 为了在 TypeScript 下不报错，添加局部声明
declare function defineNitroPlugin<T = any>(fn: (ctx: any) => T): T

import { query } from '../util/mysql'
import { sendMail } from '../util/mail'

export default defineNitroPlugin(() => {
  console.log('[email-scheduler] plugin initialized')
  let running = false

  async function runOnce() {
    if (running) return
    running = true
    try {
      const sql = `select payment_no,id, email, product_info from lin_order where status = ? and is_send_email = 0`;
      const [rows] = await query<any>(sql, ['已支付'])

      for (const r of rows) {
        const id = r.id
        const payment_no = r.payment_no
        const email = r.email
        const product_info = r.product_info || ''

        if (!email) {
          await query(`INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
            [null, `Order ${id} missing email, skip`, 'CRON', '/server/email-scheduler', 0, 0, null, new Date()])
          continue
        }

        const subject = `您的订单已支付 — 订单 ${payment_no}`
        const html = `<p>您好，</p><p>您购买的商品信息：</p><pre>${product_info}</pre><p>谢谢！</p>`

        try {
          const res = await sendMail(email, subject, html)
          if (res.ok) {
            await query(`update lin_order set is_send_email = 1 where id = ?`, [id])
            await query(`INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
              [null, `send mail success to ${email} for order ${id}`, 'CRON', '/server/email-scheduler', 0, 0, null, new Date()])
          } else {
            await query(`INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
              [null, `send mail failed to ${email} for order ${id}: ${String(res.error)}`, 'CRON', '/server/email-scheduler', 0, 0, null, new Date()])
          }
        } catch (err) {
          await query(`INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
            [null, `send mail error to ${email} for order ${id}: ${String(err)}`, 'CRON', '/server/email-scheduler', 0, 0, null, new Date()])
        }
      }
    } catch (e) {
      try { await query(`INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
        [null, `email-scheduler top-level error: ${String(e)}`, 'CRON', '/server/email-scheduler', 0, 0, null, new Date()]) } catch (ee) { /* ignore */ }
    } finally {
      running = false
    }
  }

  // 启动时立即运行一次，然后每10s运行
  setTimeout(() => void runOnce(), 1000)
  setInterval(() => void runOnce(), 10 * 1000)
})
